package utils

import (
	"cr.org/constant"
	"errors"
	"github.com/golang-jwt/jwt"
	"time"
)

var (
	TokenExpiredAt   = errors.New("Token is expired")
	TokenNotValidYet = errors.New("Token not active yet")
	TokenMalformed   = errors.New("That's not even a token")
	TokenInvalid     = errors.New("Couldn't handle this token:")
)

type JWT struct {
	SigningKey []byte
}

type CustomClaims struct {
	BaseClaims
	jwt.StandardClaims
}

type BaseClaims struct {
	UserID    int64
	Username  string
	Nickname  string
	AccountLv int
	Role      []string
}

func NewJWT() *JWT {
	return &JWT{
		[]byte(constant.JWTSigningKey),
	}
}

// CreateToken 创建一个token
func (j *JWT) CreateToken(baseClaims BaseClaims, exp int64) (string, error) {
	claims := CustomClaims{
		BaseClaims: baseClaims,
		StandardClaims: jwt.StandardClaims{ // nolint
			NotBefore: time.Now().Unix() - 1000, // 签名生效时间
			ExpiresAt: time.Now().Unix() + exp,  // 过期时间 7天  配置文件
			Issuer:    constant.JWTIssuer,       // 签名的发行者
			Subject:   "all",                    // 区分客户端和服务端，暂时不做区分
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(j.SigningKey)
}

// ParseToken 解析 token
func (j *JWT) ParseToken(tokenString string) (*CustomClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (i interface{}, e error) {
		return j.SigningKey, nil
	})
	if err != nil {
		if ve, ok := err.(*jwt.ValidationError); ok { // nolint
			if ve.Errors&jwt.ValidationErrorMalformed != 0 {
				return nil, TokenMalformed
			} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
				// Token is expired
				return nil, TokenExpiredAt
			} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
				return nil, TokenNotValidYet
			} else {
				return nil, TokenInvalid
			}
		}
	}
	if token != nil {
		if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {
			return claims, nil
		}
		return nil, TokenInvalid

	} else {
		return nil, TokenInvalid
	}
}
